/**
 * *************************************
 * Copyright(c)2016 Dingdang Yixia 
 * All Rights Reserved.
 *
 * @File: DifferBusinessServiceImpl.java
 * @Package: com.ddyx.service.impl
 * @Description:
 * 
 * @Version: V1.0
 * @Author: Yidong.Xiang
 * @Date: 2018年8月21日 下午10:00:56
 * 
 * *************************************
 */
package com.ddyx.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.alibaba.fastjson.JSONObject;
import com.ddyx.entity.Goods;
import com.ddyx.entity.GoodsStock;
import com.ddyx.entity.Order;
import com.ddyx.entity.OrderLogistics;
import com.ddyx.entity.StoreStock;
import com.ddyx.mapper.GoodsMapper;
import com.ddyx.mapper.GoodsStockMapper;
import com.ddyx.mapper.OrderLogisticsMapper;
import com.ddyx.mapper.OrderMapper;
import com.ddyx.mapper.StoreStockMapper;
import com.ddyx.model.domain.GoodsInfo;
import com.ddyx.model.domain.GoodsSku;
import com.ddyx.model.domain.OrderDetails;
import com.ddyx.model.domain.OrderInfo;
import com.ddyx.model.request.CheckRefundStatusRequest;
import com.ddyx.model.request.DownloadProductRequest;
import com.ddyx.model.request.GetOrderRequest;
import com.ddyx.model.request.GetRefundRequest;
import com.ddyx.model.request.PolymallHttpRequest;
import com.ddyx.model.request.SendOrderRequest;
import com.ddyx.model.request.SyncStockRequest;
import com.ddyx.model.request.UpdateSellerMemoRequest;
import com.ddyx.model.response.CheckRefundStatusResponse;
import com.ddyx.model.response.DownloadProductResponse;
import com.ddyx.model.response.GetOrderResponse;
import com.ddyx.model.response.GetRefundResponse;
import com.ddyx.model.response.SendOrderResponse;
import com.ddyx.model.response.SyncStockResponse;
import com.ddyx.model.response.UpdateSellerMemoResponse;
import com.ddyx.service.DifferBusinessService;

import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName: DifferBusinessServiceImpl.java
 * @Module: 菠萝派商城接入API实现类
 * @Description: 
 * 
 * @author: Yidong.Xiang
 * @date: 2018年8月21日 下午10:00:56
 * 
 */
@Slf4j
@Service("differBusinessService")
public class DifferBusinessServiceImpl implements DifferBusinessService{
	final static String GetOrder = "Differ.JH.Business.GetOrder";
	final static String CheckRefundStatus = "Differ.JH.Business.CheckRefundStatus";
	final static String Send = "Differ.JH.Business.Send";
	final static String UpdateSellerMemo = "Differ.JH.Business.UpdateSellerMemo";
	final static String DownloadProduct = "Differ.JH.Business.DownloadProduct";
	final static String SyncStock = "Differ.JH.Business.SyncStock";
	final static String GetRefund = "Differ.JH.Business.GetRefund";
	static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
	@Resource 
	GoodsMapper goodsMapper;
	@Resource
	OrderMapper orderMapper;
	@Resource 
	OrderLogisticsMapper orderLogisticsMapper;
	@Resource
	GoodsStockMapper goodsStockMapper;
	@Resource 
	StoreStockMapper storeStockMapper;
	
	@Override
//	public JSONObject response(String method, String appkey, String token, String bizcontent, String sign) {
	public JSONObject response(PolymallHttpRequest request) {
		//签名验证
		if(request.getMethod().equals(GetOrder))
			return parseResponse(getOrder(JSONObject.parseObject(request.getBizcontent(), GetOrderRequest.class)));

		if(request.getMethod().equals(CheckRefundStatus))
			return parseResponse(checkRefundStatus(JSONObject.parseObject(request.getBizcontent(),CheckRefundStatusRequest.class)));
		
		if(request.getMethod().equals(Send))
			return parseResponse(send(JSONObject.parseObject(request.getBizcontent(), SendOrderRequest.class)));
		
		if(request.getMethod().equals(UpdateSellerMemo))
			return parseResponse(updateSellerMemo(JSONObject.parseObject(request.getBizcontent(), UpdateSellerMemoRequest.class)));
		
		if(request.getMethod().equals(DownloadProduct))
			return parseResponse(downloadProduct(request.getStoreno(),JSONObject.parseObject(request.getBizcontent(), DownloadProductRequest.class)));
		
		if(request.getMethod().equals(SyncStock))
			return parseResponse(syncStock(request.getStoreno(),JSONObject.parseObject(request.getBizcontent(), SyncStockRequest.class)));
		
		return new JSONObject();
	}
	
	@Override
	public GetOrderResponse getOrder(GetOrderRequest request) {
		GetOrderResponse result = new GetOrderResponse();
		try {
			String orderId = request.getPlatOrderNo();
			String startTime = request.getStartTime();
			String endTime = request.getEndTime();
			String timeType = request.getTimeType();
			if("JH_01".equals(timeType))
				timeType = "update_time";
			else 
				timeType="create_time";
			String orderStatus = request.getOrderStatus();
			int start = getStart(request.getPageIndex(),request.getPageSize());
			int size = request.getPageSize();
			int totalcount = orderMapper.countOrder(orderStatus, orderId, startTime, endTime, timeType);
			if(totalcount==0)
				return result;
			result.setNumtotalorder(totalcount);
			List<OrderInfo> orderlist = orderMapper.getOrder(orderStatus, orderId, startTime, endTime, timeType, start, size);
			
			List<OrderInfo> orderResult = new ArrayList<OrderInfo>();
			for(OrderInfo order:orderlist)
			{
				List<OrderDetails> goodinfos = orderMapper.getOrderDetails(order.getPlatOrderNo());
				order.setGoodinfos(goodinfos);
				orderResult.add(order);
			}
			result.setOrders(orderResult);
			
		}catch(Exception e) {
			log.error("[订单下载接口]",e);
			result.setCode(GetOrderResponse.FAIL_CODE);
			result.setMessage(e.getMessage());
			return result;
		}
		return result;
	}

	@Override
	public CheckRefundStatusResponse checkRefundStatus(CheckRefundStatusRequest request) {
		//未实现部分退歀逻辑
		CheckRefundStatusResponse result = new CheckRefundStatusResponse();
		try {
			String orderId = request.getOrderID();
			String status = "JH_07";//默认没有退款
			result.setRefundStatus(status);
			
			Order query = new Order();
			query.setId(orderId);
			Order order = orderMapper.selectOne(query);
			if(order==null)
			{
				result.setRefundStatusdescription("订单不存在，无退款");
				return result;
			}
			String orderStatus = order.getOrderStatus();
			if(orderStatus==null || "".equals(orderStatus))
			{
				result.setRefundStatusdescription("订单状态空，无退款");
				return result;
			}
			orderStatus = orderStatus.toUpperCase();
			//退款申请AU、退款中RU、已退款RS、退款失败RF
			if("AU".equals(orderStatus)
				||"RU".equals(orderStatus)
				||"RF".equals(orderStatus))
			{
				result.setRefundStatus("JH_01");
				result.setRefundStatusdescription("买家已经申请退款等待卖家同意");
			}
			else if("RS".equals(orderStatus))
			{
				result.setRefundStatus("JH_06");
				result.setRefundStatusdescription("退款成功");	
			}
			else
			{
				result.setRefundStatus(status);
				result.setRefundStatusdescription("无退款");	
			}
		}catch(Exception e) {
			log.error("[检测退款接口]",e);
			result.setCode(CheckRefundStatusResponse.FAIL_CODE);
			result.setMessage(e.getMessage());
			return result;
		}
		return result;
	}

	@Override
	public SendOrderResponse send(SendOrderRequest request) {
		SendOrderResponse result = new SendOrderResponse();
		try {
			Date now = sdf.parse(sdf.format(new Date()));
			String orderId = request.getPlatOrderNo();
			int isSplit = request.getIsSplit();
			if(isSplit==1)//拆单发货
			{	
				int a =0;
				//2）部分发货：更新订单发货状态，更新订单明细货品发货数量和时间，更新已发货货品库存实物数量
			}
			else //整单发货
			{
				//1）整单发货：更新订单发货状态，更新订单明细货品发货数量和时间，更新已发货货品库存实物数量
				OrderLogistics logis = new 	OrderLogistics();
				logis.setOrderId(orderId);
				logis.setLogisticsName(request.getLogisticName());
				logis.setLogisticsNo(request.getLogisticNo());
				logis.setCreate_time(now);
				boolean success =competeShipped(orderId,logis);
			}
			//订单发货操作执行：
		}catch(Exception e) {
			log.error("[订单发货接口]",e);
			result.setCode(SendOrderResponse.FAIL_CODE);
			result.setMessage(e.getMessage());
			return result;
		}
		return result;
	}

	@Override
	public UpdateSellerMemoResponse updateSellerMemo(UpdateSellerMemoRequest request) {
		UpdateSellerMemoResponse result = new UpdateSellerMemoResponse();
		try{
			String orderId = request.getPlatOrderNo();
			String remark = request.getSellerMemo();
			orderMapper.updateOrderRemark(orderId, remark);
		}catch(Exception e) {
			log.error("[修改订单备注接口]",e);
			result.setCode(UpdateSellerMemoResponse.FAIL_CODE);
			result.setMessage(e.getMessage());
			return result;
		}
		return result;
	}

	@Override
	public DownloadProductResponse downloadProduct(String storeNo,DownloadProductRequest request) {
		DownloadProductResponse result = new DownloadProductResponse();
		try {
			String searchName = request.getProductName();
			String goodsId = request.getProductId();
			String soldout = request.getStatus();
//			String storeNo = request.getWhsecode();
			int start = getStart(request.getPageIndex(),request.getPageSize());
			int size = request.getPageSize();
			int totalcount = goodsMapper.countGoods(storeNo,goodsId, soldout, searchName);
			if(totalcount==0)
				return result;
			result.setTotalcount(totalcount);
			List<GoodsInfo> goodslist = goodsMapper.getGoodsList(storeNo, goodsId, soldout, searchName, start, size);
			
			List<GoodsInfo> stockGoods = new ArrayList<GoodsInfo>();
			for(GoodsInfo goods:goodslist)
			{
				List<GoodsSku> skus = goodsMapper.getGoodsSku(storeNo, goods.getPlatProductID());
				goods.setSkus(skus);
				stockGoods.add(goods);
			}
			result.setGoodslist(stockGoods);
			
		}catch(Exception e) {
			log.error("[商品下载接口]",e);
			result.setCode(DownloadProductResponse.FAIL_CODE);
			result.setMessage(e.getMessage());
			return result;
		}
		return result;
	}

	@Override
	public SyncStockResponse syncStock(String storeNo,SyncStockRequest request) {
		SyncStockResponse result = new SyncStockResponse();
		try {
			String id = request.getSkuID();
			int goodsQty = request.getQuantity();
			String outerId = request.getOuterID();
			String[] code = outerId.split("~");
			String goodsId = code[0];
			String goodsCode = code[1];
			String barCode = request.getOutSkuID();
			GoodsStock sku = goodsStockMapper.selectByPrimaryKey(Integer.parseInt(id));
			Goods goods = goodsMapper.selectByPrimaryKey(Integer.parseInt(goodsId));
//			System.out.println("{"+id+","+storeNo+","+goodsId+","+","+goodsCode+","+sku.getSpecsName()+","+goodsQty+","+barCode+"}");
			int r = goodsMapper.updateStoreGoodsQty(storeNo, sku.getGoodsId(), sku.getSpecsName(), goodsQty);//更新仓库的实物库存数
			if(r==0)
			{//新增店铺库存
				StoreStock ss = new StoreStock();
				ss.setStoreNo(storeNo);
				ss.setGoodsId(sku.getGoodsId());
				ss.setGoodsCode(goodsCode);
				ss.setSpecsName(sku.getSpecsName());
				ss.setBarCode(sku.getBarCode());
				ss.setGoodsColor(goods.getGoodsColor());
				ss.setGoodsQty(goodsQty);
				storeStockMapper.insert(ss);
			}
			r = goodsMapper.sumStockGoodsQty(id,sku.getGoodsId(), sku.getSpecsName());//更新sku汇总数据
			result.setQuantity(goodsQty);
			result.setCode(SyncStockResponse.SUCCESS_CODE);
			result.setMessage("库存同步记录："+r);
		}catch(Exception e) {
			log.error("[商品库存同步接口]",e);
			result.setCode(SyncStockResponse.FAIL_CODE);
			result.setMessage(e.getMessage());
			return result;
		}
		return result;
	}

	@Override
	public GetRefundResponse getRefund(GetRefundRequest request) {
		// TODO Auto-generated method stub
		return null;
	}
	/**
	 * 整单发货业务处理
	 * @param orderId
	 * @param logis
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	private boolean competeShipped(String orderId,OrderLogistics logis)
	{
		try {
			orderMapper.updateLogisticStatus(orderId,"LU");//更新订单发货状态为LU
			orderMapper.updateOrderShippedQty(orderId);//更新订单发货数量和发货时间
			orderLogisticsMapper.insert(logis);//记录发货的物流名称和运单号
			return true;
		}catch(Exception e) {
			log.error("[商品库存同步接口]",e);
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return false;
		}
	}
	private int getStart(int page ,int size)
	{
		int start = 0;
		if(size<1)
			size=10;//默认每页10条

		if(page<1)
			page = 1;//默认第1页
		start = (page-1)*size;
		return start;
	}
	private JSONObject parseResponse(Object javaObject)
	{
		return JSONObject.parseObject(JSONObject.toJSONString(javaObject));
	}
	private static String sign(String sign) {
		
		return "";
	}
	private static String md5(String str) {
		
		return "";
	}
}
